package com.jvtd.demo.amap;

import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationQualityReport;
import com.jvtd.base.JvtdActivity;
import com.jvtd.demo.R;
import com.jvtd.gd_location.JvtdLocation;
import com.jvtd.gd_location.JvtdLocationCallBack;
import com.jvtd.gd_location.JvtdLocationOption;
import com.jvtd.widget.toast.JvtdToast;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class GdLocationActivity extends JvtdActivity
{
  private JvtdToast mToast;
  private Switch swOnceLocation;
  private Switch swOnceLocationLatest;
  private EditText etInterval;
  private EditText etHttpTimeOut;
  private TextView tvLocationMsg;
  private TextView tvAddressMsg;

  @Override
  protected void bindView()
  {
    TextView tvTitle = findViewById(R.id.tv_title);
    tvTitle.setText("高德定位模块");
    Toolbar mToolbar = findViewById(R.id.tool_bar);
    setToolbar(mToolbar, true);

    // 配置参数
    Switch swOpenOption = findViewById(R.id.sw_open_option);
    swOpenOption.setChecked(JvtdLocation.getInstance(this).isOpenLocationOption());
    swOpenOption.setOnCheckedChangeListener((compoundButton, checked) ->
    {
      if (checked)
        JvtdLocation.getInstance(GdLocationActivity.this).openLocationOption();
      else
        JvtdLocation.getInstance(GdLocationActivity.this).closeLocationOption();
    });

    // 定位场景
    Spinner spLocationPurpose = findViewById(R.id.sp_location_purpose);
    ArrayAdapter<CharSequence> locationPurposeAdapter = ArrayAdapter.createFromResource(this, R.array.location_purpose, android.R.layout.simple_spinner_item);
    locationPurposeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spLocationPurpose.setAdapter(locationPurposeAdapter);
    spLocationPurpose.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
    {
      @Override
      public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l)
      {
        switch (position)
        {
          case 0:
            if (JvtdLocation.getInstance(GdLocationActivity.this).isOpenLocationOption())
              mToast.showMessage("默认即无场景, 且设置过其他场景后,无法切换会无场景状态", 500);
            break;

          case 1:
            JvtdLocation.getInstance(GdLocationActivity.this).setLocationPurpose(JvtdLocationOption.LocationPurpose.SignIn);
            break;

          case 2:
            JvtdLocation.getInstance(GdLocationActivity.this).setLocationPurpose(JvtdLocationOption.LocationPurpose.Transport);
            break;

          case 3:
            JvtdLocation.getInstance(GdLocationActivity.this).setLocationPurpose(JvtdLocationOption.LocationPurpose.Sport);
            break;
        }
      }

      @Override
      public void onNothingSelected(AdapterView<?> adapterView)
      {

      }
    });

    // 定位模式
    Spinner spLocationMode = findViewById(R.id.sp_location_mode);
    ArrayAdapter<CharSequence> locationModeAdapter = ArrayAdapter.createFromResource(this, R.array.location_mode, android.R.layout.simple_spinner_item);
    locationModeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spLocationMode.setAdapter(locationModeAdapter);
    spLocationMode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
    {
      @Override
      public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l)
      {
        switch (position)
        {
          case 0:
            if (JvtdLocation.getInstance(GdLocationActivity.this).isOpenLocationOption())
              JvtdLocation.getInstance(GdLocationActivity.this).setLocationMode(JvtdLocationOption.LocationMode.Hight_Accuracy);
            break;

          case 1:
            JvtdLocation.getInstance(GdLocationActivity.this).setLocationMode(JvtdLocationOption.LocationMode.Battery_Saving);
            break;

          case 2:
            JvtdLocation.getInstance(GdLocationActivity.this).setLocationMode(JvtdLocationOption.LocationMode.Device_Sensors);
            break;
        }
      }

      @Override
      public void onNothingSelected(AdapterView<?> adapterView)
      {

      }
    });

    // 单次定位
    swOnceLocation = findViewById(R.id.sw_once_location);
    swOnceLocation.setOnCheckedChangeListener((compoundButton, checked) -> JvtdLocation.getInstance(GdLocationActivity.this).setOnceLocation(checked));

    // 单次定位(返回最近3s内精度最高的一次定位结果)
    swOnceLocationLatest = findViewById(R.id.sw_once_location_latest);
    swOnceLocationLatest.setOnCheckedChangeListener((compoundButton, checked) ->
    {
      if (checked)
        swOnceLocation.setChecked(true);
      JvtdLocation.getInstance(GdLocationActivity.this).setOnceLocationLatest(checked);
    });

    // 持续定位自定义时间间隔
    etInterval = findViewById(R.id.et_interval);
    TextView btnInterval = findViewById(R.id.btn_interval);
    btnInterval.setOnClickListener(view ->
    {
      swOnceLocation.setChecked(false);
      swOnceLocationLatest.setChecked(false);
      JvtdLocation.getInstance(GdLocationActivity.this).setInterval(Integer.parseInt(etInterval.getText().toString().trim()));
    });

    // 是否返回地址信息
    Switch swNeedAddress = findViewById(R.id.sw_need_address);
    swNeedAddress.setOnCheckedChangeListener((compoundButton, checked) -> JvtdLocation.getInstance(GdLocationActivity.this).setNeedAddress(checked));

    // 设置是否开启定位缓存机制(默认开启)
    Switch swLocationCache = findViewById(R.id.sw_location_cache);
    swLocationCache.setOnCheckedChangeListener((compoundButton, checked) -> JvtdLocation.getInstance(GdLocationActivity.this).setLocationCacheEnable(checked));

    // 设置是否允许模拟软件Mock位置结果，多为模拟GPS定位结果，默认为true，允许模拟位置
    Switch swMock = findViewById(R.id.sw_mock);
    swMock.setOnCheckedChangeListener((compoundButton, checked) -> JvtdLocation.getInstance(GdLocationActivity.this).setMockEnable(checked));

    // 设置定位请求超时时间，默认为30秒
    etHttpTimeOut = findViewById(R.id.et_http_time_out);
    TextView btnHttpTimeOut = findViewById(R.id.btn_http_time_out);
    btnHttpTimeOut.setOnClickListener(view -> JvtdLocation.getInstance(GdLocationActivity.this).setHttpTimeOut(Integer.parseInt(etHttpTimeOut.getText().toString().trim())));

    // 开始定位
    Button btnStartLocation = findViewById(R.id.btn_start_location);
    btnStartLocation.setOnClickListener(view -> JvtdLocation.getInstance(GdLocationActivity.this).startLocation());

    // 停止定位
    Button btnStopLocation = findViewById(R.id.btn_stop_location);
    btnStopLocation.setOnClickListener(view ->
    {
      JvtdLocation.getInstance(GdLocationActivity.this).stopLocation();
      tvLocationMsg.setText("");
      tvAddressMsg.setText("");
    });

    tvLocationMsg = findViewById(R.id.tv_location_msg);
    tvAddressMsg = findViewById(R.id.tv_address_msg);
  }

  @Override
  protected void getLayout()
  {
    setContentView(R.layout.activity_gd_map);
  }

  @Override
  protected void initViewAndData()
  {
    mToast = new JvtdToast(this, JvtdToast.FLAG_BOTTOM);

    JvtdLocation.getInstance(this).setApiKey("707fb1ed21b6b4ba91d71cb818f3b805").init(new JvtdLocationCallBack()
    {
      @Override
      public void onLocationChanged(AMapLocation aMapLocation)
      {
        /**
         * 定位成功
         *
         * @param aMapLocation 位置信息数据
         *                     <p>
         *                     //可在其中解析amapLocation获取相应内容。
         *                     aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
         *                     aMapLocation.getLatitude();//获取纬度
         *                     aMapLocation.getLongitude();//获取经度
         *                     aMapLocation.getAccuracy();//获取精度信息
         *                     <p>
         *                     // 模式为仅设备模式(Device_Sensors)时无以下信息
         *                     aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
         *                     aMapLocation.getCountry();//国家信息
         *                     aMapLocation.getProvince();//省信息
         *                     aMapLocation.getCity();//城市信息
         *                     aMapLocation.getDistrict();//城区信息
         *                     aMapLocation.getStreet();//街道信息
         *                     aMapLocation.getStreetNum();//街道门牌号信息
         *                     aMapLocation.getCityCode();//城市编码
         *                     aMapLocation.getAdCode();//地区编码
         *                     aMapLocation.getAoiName();//获取当前定位点的AOI信息
         *                     aMapLocation.getBuildingId();//获取当前室内定位的建筑物Id
         *                     aMapLocation.getFloor();//获取当前室内定位的楼层
         *                     aMapLocation.getGpsAccuracyStatus();//获取GPS的当前状态
         *                     //获取定位时间
         *                     SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         *                     Date date = new Date(aMapLocation.getTime());
         *                     df.format(date);
         */
        StringBuilder locationMsg = new StringBuilder();
        locationMsg.append("定位成功" + "\n");
        locationMsg.append("定位类型: ").append(aMapLocation.getLocationType()).append("\n");
        locationMsg.append("经    度    : ").append(aMapLocation.getLongitude()).append("\n");
        locationMsg.append("纬    度    : ").append(aMapLocation.getLatitude()).append("\n");
        locationMsg.append("精    度    : ").append(aMapLocation.getAccuracy()).append("米").append("\n");
        locationMsg.append("提供者    : ").append(aMapLocation.getProvider()).append("\n");
        //定位完成的时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        Date date = new Date(aMapLocation.getTime());
        String dateStr = df.format(date);
        locationMsg.append("定位时间: ").append(dateStr).append("\n");
        locationMsg.append("***定位质量报告***").append("\n");
        locationMsg.append("* WIFI开关：").append(aMapLocation.getLocationQualityReport().isWifiAble() ? "开启" : "关闭").append("\n");
        locationMsg.append("* GPS状态：").append(getGPSStatusString(aMapLocation.getLocationQualityReport().getGPSStatus())).append("\n");
        locationMsg.append("* GPS星数：").append(aMapLocation.getLocationQualityReport().getGPSSatellites()).append("\n");
        locationMsg.append("* 网络类型：").append(aMapLocation.getLocationQualityReport().getNetworkType()).append("\n");
        locationMsg.append("* 网络耗时：").append(aMapLocation.getLocationQualityReport().getNetUseTime()).append("\n");


        StringBuilder addressMsg = new StringBuilder();
        addressMsg.append("速    度    : ").append(aMapLocation.getSpeed()).append("米/秒").append("\n");
        addressMsg.append("角    度    : ").append(aMapLocation.getBearing()).append("\n");
        // 获取当前提供定位服务的卫星个数
        addressMsg.append("星    数    : ").append(aMapLocation.getSatellites()).append("\n");
        addressMsg.append("国    家    : ").append(aMapLocation.getCountry()).append("\n");
        addressMsg.append("省            : ").append(aMapLocation.getProvince()).append("\n");
        addressMsg.append("市            : ").append(aMapLocation.getCity()).append("\n");
        addressMsg.append("城市编码 : ").append(aMapLocation.getCityCode()).append("\n");
        addressMsg.append("区            : ").append(aMapLocation.getDistrict()).append("\n");
        addressMsg.append("区域 码   : ").append(aMapLocation.getAdCode()).append("\n");
        addressMsg.append("地    址    : ").append(aMapLocation.getAddress()).append("\n");
        addressMsg.append("兴趣点    : ").append(aMapLocation.getPoiName()).append("\n");

        tvLocationMsg.setText(locationMsg.toString());
        tvAddressMsg.setText(addressMsg.toString());
      }

      @Override
      public void locationError(int errorCode, String errorInfo)
      {
        mToast.showMessage("errorCode = " + errorCode + ", errorInfo = " + errorInfo, 500);
      }

      @Override
      public void onCustomError(String errorInfo)
      {
        mToast.showMessage("errorInfo = " + errorInfo, 500);
      }
    });
  }

  /**
   * 获取GPS状态的字符串
   *
   * @param statusCode GPS状态码
   */
  private String getGPSStatusString(int statusCode)
  {
    String str = "";
    switch (statusCode)
    {
      case AMapLocationQualityReport.GPS_STATUS_OK:
        str = "GPS状态正常";
        break;
      case AMapLocationQualityReport.GPS_STATUS_NOGPSPROVIDER:
        str = "手机中没有GPS Provider，无法进行GPS定位";
        break;
      case AMapLocationQualityReport.GPS_STATUS_OFF:
        str = "GPS关闭，建议开启GPS，提高定位质量";
        break;
      case AMapLocationQualityReport.GPS_STATUS_MODE_SAVING:
        str = "选择的定位模式中不包含GPS定位，建议选择包含GPS定位的模式，提高定位质量";
        break;
      case AMapLocationQualityReport.GPS_STATUS_NOGPSPERMISSION:
        str = "没有GPS定位权限，建议开启gps定位权限";
        break;
    }
    return str;
  }

  @Override
  protected void onResume()
  {
    super.onResume();
    mToast.onResume();
  }

  @Override
  protected void onPause()
  {
    super.onPause();
    mToast.onPause();
  }

  @Override
  protected void onDestroy()
  {
    super.onDestroy();
    JvtdLocation.getInstance(GdLocationActivity.this).closeLocationOption();
    JvtdLocation.getInstance(GdLocationActivity.this).stopLocation();
    JvtdLocation.getInstance(GdLocationActivity.this).destoryLocation();
  }
}
